package com.heliming.data.utils;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
	 
    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
 
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String header = request.getHeader(JwtTokenUtils.HEADER_STRING);
		if (header == null || !header.startsWith(JwtTokenUtils.TOKEN_PERFIX)) {
			chain.doFilter(request, response);
			return;
		}
		UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
		SecurityContextHolder.getContext().setAuthentication(authentication);
		chain.doFilter(request, response);
	}
    
 
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(JwtTokenUtils.HEADER_STRING).replace(JwtTokenUtils.TOKEN_PERFIX, "").trim();
        ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
        
        if (token != null) {
            String username = JwtTokenUtils.getClaimsFromToken(token).getSubject();
            if (username != null) {
            	if ("heliming2".equals(username)) {
            		authorities.add(new SimpleGrantedAuthority("ROLE_WRITER"));
            	} 
                return new UsernamePasswordAuthenticationToken(username, null, authorities);
            }
            return null;
        }
        return null;
    }
 
}
